/**
 * 时区转换和市场时间工具
 */

export interface MarketScheduleConfig {
  open: string; // 格式: "HH:mm"
  close: string;
  timezone: string; // IANA时区，如 "America/New_York"
  breakStart?: string;
  breakEnd?: string;
}

export const MARKET_SCHEDULES: Record<string, MarketScheduleConfig> = {
  CN: { 
    open: '09:30', 
    close: '15:00', 
    timezone: 'Asia/Shanghai',
    breakStart: '11:30',
    breakEnd: '13:00',
  },
  HK: { 
    open: '09:30', 
    close: '16:00', 
    timezone: 'Asia/Hong_Kong',
    breakStart: '12:00',
    breakEnd: '13:00',
  },
  JP: { 
    open: '09:00', 
    close: '15:00', 
    timezone: 'Asia/Tokyo',
    breakStart: '11:30',
    breakEnd: '12:30',
  },
  KR: {
    open: '09:00',
    close: '15:30',
    timezone: 'Asia/Seoul',
  },
  TW: {
    open: '09:00',
    close: '13:30',
    timezone: 'Asia/Taipei',
  },
  US: { 
    open: '09:30', 
    close: '16:00', 
    timezone: 'America/New_York',
  },
  UK: { 
    open: '08:00', 
    close: '16:30', 
    timezone: 'Europe/London',
  },
  DE: { 
    open: '09:00', 
    close: '17:30', 
    timezone: 'Europe/Berlin',
  },
  FR: {
    open: '09:00',
    close: '17:30',
    timezone: 'Europe/Paris',
  },
};

export type MarketStatusType = 'trading' | 'pre_market' | 'after_hours' | 'closed';

/**
 * 判断市场当前状态
 */
export function getMarketStatus(marketCode: string): MarketStatusType {
  const schedule = MARKET_SCHEDULES[marketCode];
  if (!schedule) {
    return 'closed';
  }

  try {
    const now = new Date();
    const marketTime = new Date(now.toLocaleString('en-US', { timeZone: schedule.timezone }));
    const day = marketTime.getDay();

    // 周末休市
    if (day === 0 || day === 6) {
      return 'closed';
    }

    const currentMinutes = marketTime.getHours() * 60 + marketTime.getMinutes();
    const [openHour, openMinute] = schedule.open.split(':').map(Number);
    const [closeHour, closeMinute] = schedule.close.split(':').map(Number);
    const openMinutes = openHour * 60 + openMinute;
    const closeMinutes = closeHour * 60 + closeMinute;

    // 午休时间
    if (schedule.breakStart && schedule.breakEnd) {
      const [breakStartHour, breakStartMinute] = schedule.breakStart.split(':').map(Number);
      const [breakEndHour, breakEndMinute] = schedule.breakEnd.split(':').map(Number);
      const breakStartMinutes = breakStartHour * 60 + breakStartMinute;
      const breakEndMinutes = breakEndHour * 60 + breakEndMinute;

      if (currentMinutes >= breakStartMinutes && currentMinutes < breakEndMinutes) {
        return 'closed';
      }
    }

    // 交易中
    if (currentMinutes >= openMinutes && currentMinutes < closeMinutes) {
      return 'trading';
    }

    // 盘前（开盘前1小时内）
    if (currentMinutes >= openMinutes - 60 && currentMinutes < openMinutes) {
      return 'pre_market';
    }

    // 盘后（收盘后4小时内）
    if (currentMinutes >= closeMinutes && currentMinutes < closeMinutes + 240) {
      return 'after_hours';
    }

    return 'closed';
  } catch (error) {
    console.error('Error getting market status:', error);
    return 'closed';
  }
}

/**
 * 获取市场当地时间
 */
export function getMarketLocalTime(marketCode: string): Date {
  const schedule = MARKET_SCHEDULES[marketCode];
  if (!schedule) {
    return new Date();
  }

  const now = new Date();
  const localTimeString = now.toLocaleString('en-US', { timeZone: schedule.timezone });
  return new Date(localTimeString);
}

/**
 * 格式化市场时间
 */
export function formatMarketTime(marketCode: string): string {
  const marketTime = getMarketLocalTime(marketCode);
  return marketTime.toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit',
    hour12: false,
  });
}

/**
 * 获取市场状态图标
 */
export function getMarketStatusIcon(status: MarketStatusType): string {
  const iconMap: Record<MarketStatusType, string> = {
    trading: '🟢',
    pre_market: '🟡',
    after_hours: '🟡',
    closed: '⚫',
  };
  return iconMap[status];
}

/**
 * 获取市场状态文本
 */
export function getMarketStatusText(status: MarketStatusType): string {
  const textMap: Record<MarketStatusType, string> = {
    trading: '交易中',
    pre_market: '盘前',
    after_hours: '盘后',
    closed: '休市',
  };
  return textMap[status];
}

/**
 * 判断是否应该刷新该市场数据
 */
export function shouldRefreshMarket(marketCode: string): boolean {
  const status = getMarketStatus(marketCode);
  return status === 'trading' || status === 'pre_market' || status === 'after_hours';
}

/**
 * 获取市场的刷新间隔（毫秒）
 */
export function getMarketRefreshInterval(marketCode: string): number {
  const status = getMarketStatus(marketCode);
  
  switch (status) {
    case 'trading':
      return 60000; // 交易中：60秒
    case 'pre_market':
    case 'after_hours':
      return 300000; // 盘前盘后：5分钟
    case 'closed':
      return 0; // 休市：不刷新
    default:
      return 0;
  }
}

